package cn.alterzhang.www.test;

import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.framework.recipes.locks.InterProcessMutex;
import org.apache.curator.retry.ExponentialBackoffRetry;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.CountDownLatch;

/**
 * Created by zhangshuhan on 2019/1/31.
 */
public class ZKLock {
    static CuratorFramework client = CuratorFrameworkFactory.newClient("198.181.39.68:2181", 5000, 3000, new ExponentialBackoffRetry(1000, 3));
    static String lockPath = "/lock_path";

    public static void main(String[] args) {
        client.start();
        InterProcessMutex lock = new InterProcessMutex(client, lockPath);
        CountDownLatch countDown = new CountDownLatch(1);
        for (int i = 0; i < 10; i++) {
            new Thread(new Runnable() {
                @Override
                public void run() {

                    try {
                        countDown.await();
                        lock.acquire();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss||SSS");
                    String orderNO = simpleDateFormat.format(new Date());
                    System.out.println(orderNO);
                    try {
                        lock.release();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }).start();
        }
        countDown.countDown();
    }
}
